<?php

namespace App\Logics;


use App\Models\Event;
use App\Models\EventCollect;
use App\Models\User;
use App\Models\UserAuth;
use App\Models\UserFan;
use App\Service\Base\Logic;

class EventLogic extends Logic
{

    // 活动

    // 赛事，研学
    // 赛事：列表
    // 研学：列表
    // 推荐：赛事
    // 推荐：研学

    //  这个列表单独独立出来，方便使用
    // 发起的活动

    // 获取列表
    public function getLists($myUid)
    {
        $event = $this->getEventWhere();
        $where = $event[0];
        $bang  = $event[1];

        $opt  = $this->option();
        $page = $opt->getData('page', 0, 'intval');
        $rows = $opt->getData('rows', 15, 'intval');
        $res  = $this->getEvents($where, $bang, $page, $rows);

        // 判断是否收藏
        if(!empty($res['list'])){
            $collects = (new EventCollect())->bangField(['uid', 'status'])->getList(['uid' => $myUid, 'status' => 1]);
            $collIds  = array_column($collects, 'article_id');
            foreach($res['list'] as $key => $item){
                $res['list'][$key]['is_collect'] = in_array($item['id'], $collIds) ? 1 : 0;
            }
        }

        return $res;
    }

    // 详情：返回最新的文章
    public function getNewest($event_type = '', $number = 5)
    {
        // 指定类型
        $bang  = ['is_sale', 'verify'];
        $where = [['is_sale', '=', 1], ['verify', '=', 1]];
        if($event_type){
            $bang[]  = 'event_type';
            $where[] = ['event_type', '=', $event_type];
        }
        $lists = $this->getEvents($where, $bang, 0, $number);

        return $lists;
    }

    // 推荐
    public function getPropose($number = 4)
    {
        $option = $this->option();
        $_type  = $option->getData('event_type', null, 'trim');
        $bang   = ['is_propose', 'is_sale', 'verify'];
        $where  = [['is_propose', '=', 1], ['is_sale', '=', 1], ['verify', '=', 1]];
        $where2 = [['is_sale', '=', 1], ['verify', '=', 1]];  // 如果推荐数据不够的时候 重新查询
        if($_type){
            $bang[]  = 'event_type';
            $where[] = ['event_type', '=', $_type];
        }

        $lists = $this->getEvents($where, $bang, 0, $number);

        // 如果推荐数不够 重新查询
        $count = $number - count($lists);
        if($count > 0){
            $ids = array_column($lists, 'id');
            if(empty($ids)){
                $ids = [0];
            }
            $model  = new Event();
            $lists3 = $model->where($where2)->whereNotIn('id', $ids)->get()->toArray();
            $lists  = array_merge($lists, $lists3);  // 合并
        }

        return $lists;
    }

    // 详情
    public function onShow($myUid = 0)
    {
        $option   = $this->option();
        $event_id = $option->getData('event_id', 0, 'intval');
        $channel  = $option->getData('event_type', null, 'trim');
        if(empty($event_id)){
            return $this->_returnFail('请指定要查看的记录！');
        }
        if(empty($channel)){
            return $this->_returnFail('请指定要查看的文章类型！');
        }

        $model = new Event();
        $info  = $model->isCache(true)->oneFind(['id' => $event_id, 'event_type' => $channel]);  // 'verify' => 1,
        if($info === false){
            return $this->_returnFail($model->getError());
        }
        if(empty($info)){
            return $this->_returnFail('活动不存在或者已经被删除！');
        }


        // 用户信息
        $info['user'] = (new User())->isCache(true)->oneFind(['id' => $info['uid']]);
        // 用户信息
        $info['auth'] = (new UserAuth())->isCache(true)->oneFind(['id' => $info['auth_id']]);
        // 判断是否收藏
        $info['is_collect'] = (new EventCollect())->isCollect($myUid, $event_id);
        // 判断是否关注
        $info['is_follow']   = (new UserFan())->isFollow($myUid, $info['auth_id']);
        $info['images']      = json_decode($info['images'], true);
        $info['last_second'] = $info['dead_time'] - LARAVEL_TIME; // 剩余秒数
        // 活动量
        $auth_id  = $info['auth_id'];
        $eventNos = $model->selectRaw('count(*) number')->where(['is_sale' => 1, 'verify' => 1, 'auth_id' => $auth_id])->get()->toArray();
        // 组合活动量
        $info['auth']['event_no'] = $eventNos[0]['number'];
        $info['user']['event_no'] = $eventNos[0]['number'];


        return $info;
    }

    // 软删除
    public function toSoft($myUid)
    {
        $option = $this->option();
        $_id    = $option->getData('event_id', 0, 'intval');
        if(empty($_id)){
            return $this->_returnFail('请指定删除记录');
        }

        $where  = ['id' => $_id, 'uid' => $myUid];
        $model  = new Event();
        $result = $model->isCache(true)->oneEdit($where, ['verify' => -1]);
        if($result === false){
            return $this->_returnFail($model->getError());
        }

        return $result;
    }

    // 改变（直接修改，软删除，改变状态，排序）
    public function onEdit($myUid)
    {
        $opt   = $this->option();
        $_id   = $opt->getData('event_id', 0, 'intval');
        $_type = $opt->getData("event_type", null, "trim");  // 赛事game,  研学study，沙龙salon
        if(empty($_id)){
            return $this->_returnFail('请指定修改的ID编号！');
        }
        if(empty($_type) || (!in_array($_type, ['game', 'study', 'salon']))){
            return $this->_returnFail('请指定正确的活动类型！！');
        }


        // 查找数据
        $where = ['id' => $_id, 'uid' => $myUid];
        $model = new Event();
        $info  = $model->isCache(true)->oneFind($where);
        if(empty($info)){
            return $this->_returnFail('该数据不存在或者不是你发布的内容！');
        }
        /*if($info['verify'] == 1){
            return $this->_returnFail('已经审核通过后的内容不能在修改！');
        }*/

        // 检查用户认证方式
        $userDb = new User();
        $user   = $userDb->checkUserAuth($myUid, true);
        if($user === false){
            return $this->_returnFail($userDb->getError());
        }


        $auth_id = $user['auth_id'];
        $data    = [
            //'id'          => $opt->getData("id", null, "intval"),
            //'uid'         => $myUid,
            //'auth_id'     => $auth_id,
            'event_type'   => $_type,
            'event_name'   => $opt->getData("event_name", null, "trim"),
            'organ_price'  => $opt->getData("organ_price", 0, "trim"),
            'person_price' => $opt->getData("person_price", 0, "trim"),
            'is_refund'    => $opt->getData("is_refund", null, "intval"),
            'dead_time'    => $opt->getData("dead_time", null, "intval"),
            'start_time'   => $opt->getData("start_time", null, "intval"),
            'end_time'     => $opt->getData("end_time", null, "intval"),
            'city'         => $opt->getData("city", null, "trim"),
            'address'      => $opt->getData("address", null, "trim"),
            'description'  => $opt->getData("description", null, "trim"),
            'cover'        => $opt->getData("cover", null, "trim"),
            'images'       => $opt->getData("images", null, "json_encode"),
            'is_propose'   => $opt->getData("is_propose", null, "intval"),
            'is_sale'      => $opt->getData("is_propose", 1, "intval"),
            'verify'       => $opt->getData("verify", 0, "intval"),  // 更新之后需要重新审核
            //'ctime'       => $opt->getData("ctime", null, "intval"),
            //'mtime'       => $opt->getData("mtime", null, "intval"),
        ];

        // 机构价格 与 个人价格 对比
        if($data['person_price'] && ($data['organ_price'] > $data['person_price'])){
            return $this->_returnFail('机构价不能大于个人价格！');
        }

        $data = $this->filterNull($data);
        if(empty($data)){
            return $this->_returnFail('请添加需要保存的数据！');
        }

        // 组合数据
        $data = $model->checkData($data, $where);
        if($data === false){
            return $this->_returnFail('请添加需要保存的数据！');
        }

        // 验证
        $result = $model->checkRules($data, 'edit');
        if($result === false){
            return $this->_returnFail($model->getError());
        }

        // 保存
        $result = $model->oneEdit($where, $data);
        if($result === false){
            return $this->_returnFail($model->getError());
        }

        return $result;
    }

    // 添加
    public function onAdd($myUid)
    {
        // 检查用户认证方式
        $userDb = new User();
        $user   = $userDb->checkUserAuth($myUid, true);
        if($user === false){
            return $this->_returnFail($userDb->getError());
        }

        $opt     = $this->option();
        $auth_id = $user['auth_id'];
        $_type   = $opt->getData("event_type", null, "trim");
        if(empty($_type) || (!in_array($_type, ['game', 'study', 'salon']))){
            return $this->_returnFail('请指定正确的活动类型！！');
        }

        $data = [
            //'id'          => $opt->getData("id", null, "intval"),
            'uid'          => $myUid,
            'auth_id'      => $auth_id,
            'event_type'   => $_type,
            'event_name'   => $opt->getData("event_name", null, "trim"),
            'organ_price'  => $opt->getData("organ_price", 0, "trim"),
            'person_price' => $opt->getData("person_price", 0, "trim"),
            'is_refund'    => $opt->getData("is_refund", null, "intval"),
            'dead_time'    => $opt->getData("dead_time", null, "intval"),
            'start_time'   => $opt->getData("start_time", null, "intval"),
            'end_time'     => $opt->getData("end_time", null, "intval"),
            'city'         => $opt->getData("city", null, "trim"),
            'address'      => $opt->getData("address", null, "trim"),
            'description'  => $opt->getData("description", null, "trim"),
            'cover'        => $opt->getData("cover", null, "trim"),
            'images'       => $opt->getData("images", null, "json_encode"),
            'is_propose'   => $opt->getData("is_propose", 0, "intval"),
            'is_sale'      => $opt->getData("is_propose", 1, "intval"),
            'verify'       => $opt->getData("verify", 0, "intval"),
            //'ctime'       => $opt->getData("ctime", null, "intval"),
            //'mtime'       => $opt->getData("mtime", null, "intval"),
        ];

        // 机构价格 与 个人价格 对比
        if($data['person_price'] && ($data['organ_price'] > $data['person_price'])){
            return $this->_returnFail('机构价不能大于个人价格！');
        }

        $data = $this->filterNull($data);
        if(empty($data)){
            return $this->_returnFail('请添加需要保存的数据！');
        }

        // 组合数据
        $model = new Event();
        $data  = $model->checkData($data);
        if($data === false){
            return $this->_returnFail('请添加需要保存的数据！');
        }

        // 验证
        $result = $model->checkRules($data, 'add');
        if($result === false){
            return $this->_returnFail($model->getError());
        }

        // 保存
        $result = $model->oneAdd($data);
        if($result === false){
            return $this->_returnFail($model->getError());
        }

        return $result;
    }

    ##############################################################################
    ## 设置 上架下架等操作
    public function onSale($myUid)
    {
        $option = $this->option();
        $_id    = $option->getData('event_id', 0, 'intval');
        $_value = $option->getData('value', 0, 'intval');
        if(empty($_id)){
            return $this->_returnFail('请指定操作记录');
        }
        if(!in_array($_value, [0, 1])){
            return $this->_returnFail('请指定正确上下架状态');
        }

        $where  = ['id' => $_id, 'uid' => $myUid];
        $model  = new Event();
        $result = $model->isCache(true)->oneEdit($where, ['is_sale' => $_value]);
        if($result === false){
            return $this->_returnFail($model->getError());
        }

        return $result;
    }

    ##############################################################################
    // 列表查询
    protected function getEvents($where = [], $bang = [], $page = 0, $rows = 15)
    {
        // 模型
        $start = $page ? ($page - 1) * $rows : $rows;
        $model = new Event();

        // 模型
        /*$KCache = $model->cacheKey('lists', $where);
        $lists  = $model->cacheClass()->getCache($KCache);
        if(empty($lists)){}*/
        // 执行
        if($page){
            $result = $model->bangField($bang)->listPage($where, $page, $rows, "id DESC");
        } else{
            $result = $model->bangField($bang)->getList($where, $rows, "id DESC", $start);
        }

        return $result;
    }

    // 查询条件
    protected function getEventWhere()
    {
        $option  = $this->option();
        $where   = [];
        $bang    = [];
        $c_id    = $option->getData('course_id', 0, 'intval');
        $uid     = $option->getData('uid', 0, 'intval');
        $auth_id = $option->getData('auth_id', 0, 'intval');
        $verify  = $option->getData('verify', null, 'intval');
        $is_sale = $option->getData('is_sale', null, 'intval');
        $s_id    = $option->getData('student_id', 0, 'intval');
        $is_prop = $option->getData('is_propose', null, 'intval');
        $_type   = $option->getData('event_type', null, 'trim');
        $name    = $option->getData('event_name', null, 'trim');
        $keyword = $option->getData('keyword', null, 'trim');
        if($c_id){
            $bang[]  = 'course_id';
            $where[] = ['course_id', '=', $c_id];
        }
        if($uid){
            $bang[]  = 'uid';
            $where[] = ['uid', '=', $uid];
        }
        if($auth_id){
            $bang[]  = 'auth_id';
            $where[] = ['auth_id', '=', $auth_id];
        }
        if($s_id){
            $bang[]  = 'student_id';
            $where[] = ['student_id', '=', $s_id];
        }
        if(!is_null($is_prop)){
            $bang[]  = 'is_propose';
            $where[] = ['is_propose', '=', $is_prop];
        }
        if(!is_null($verify)){
            $bang[]  = 'verify';
            $where[] = ['verify', '=', $verify];
        }
        if(!is_null($is_sale)){
            $bang[]  = 'is_sale';
            $where[] = ['is_sale', '=', $is_sale];
        }
        if($name){
            $where[] = ['event_name', 'like', "%".$name."%"];
        }
        if($_type){
            $bang[]  = 'event_type';
            $where[] = ['event_type', '=', $_type];
        }
        /*if($keyword){
            $where[] = $this->orWhere('event_name|description|address', 'like', $keyword);
            $bang    = false;
        }*/

        return [$where, $bang];
    }

}


